<template>
  <div>
    <div class="search">
      <el-card>
        <el-form :inline="true" :model="searchData" class="demo-form-inline">
          <el-form-item label="角色id">
            <el-input v-model="searchData.id" clearable placeholder="角色id" />
          </el-form-item>
          <el-form-item label="角色状态">
            <el-select v-model="searchData.region" clearable placeholder="角色状态">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="Activity time">
            <el-date-picker
              v-model="searchData.date"
              type="date"
              placeholder="Pick a date"
              clearable
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="onSearchSubmit">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="mytable">
      <el-card class="gongju">
        <addItemHandlerComponent
          @callParentaddItemHandler="
            () => {
              addItemHandler()
            }
          "
        ></addItemHandlerComponent>
      </el-card>
      <el-card>
        <TableComponent
          :tableData="tableData"
          @callParentdel="
            (id) => {
              delItemHandler(id)
            }
          "
          @updaterow="
            (row) => {
              editItemHandler(row)
            }
          "
        ></TableComponent>
      </el-card>
    </div>
    <div class="mypage">
      <el-pagination
        :total="pageParams.total"
        background
        layout="prev, pager, next"
        @change="pageChangeHandler"
      />
    </div>

    <!-- 弹框 -->
    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="800">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        :size="formSize"
        class="demo-ruleForm"
        label-width="auto"
        status-icon
        style="max-width: 600px"
      >
        <el-form-item label="角色ID" prop="id">
          <el-input v-model="ruleForm.id" />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="name">
          <el-input v-model="ruleForm.code" />
        </el-form-item>

        <el-form-item label="角色状态" prop="delivery">
          <el-switch
            v-model="ruleForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
            inline-prompt
          />
        </el-form-item>

        <el-form-item>
          <el-button
            :disabled="isSBtnDisable"
            :loading="isSBtnLoding"
            type="primary"
            @click="submitForm(ruleFormRef)"
          >
            Create
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  addRole,
  delRole,
  editRole,
  requestGetRolesPage,
  type RolesType
} from '@/service/study5/demo2'
import { type ComponentSize, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import addItemHandlerComponent from '../components/addItemHandlerComponent.vue'
import TableComponent from '../components/tableComponent.vue'
import type { id } from 'element-plus/lib/locale/index.js'

const tableData = ref<RolesType[]>([])
const pageParams = ref({
  pageNum: 1, //当前页
  pageSize: 15, //每页数量
  total: 0
})

// interface RuleForm {
//   name: string
//   region: string
//   count: string
//   date1: string
//   date2: string
//   delivery: boolean
//   location: string
//   type: string[]
//   resource: string
//   desc: string
// }

export type RuleFormInfo = {
  type: 'add' | 'edit' | 'del'
  title: string
}

// 是否显示 Dialog
const dialogFormVisible = ref(false)
const isSBtnLoding = ref(false)
const isSBtnDisable = ref(false)
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RolesType>({
  code: '',
  createTime: '',
  name: '',
  sort: 1,
  status: 1
})
const ruleFormInfo = ref<RuleFormInfo>({
  type: 'add',
  title: '添加数据'
})

// const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RolesType>>({
  id: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  name: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  code: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  status: [{ required: true, message: '不可以为空', trigger: 'blur' }]
  // region: [
  //   {
  //     required: true,
  //     message: 'Please select Activity zone',
  //     trigger: 'change'
  //   }
  // ],
  // count: [
  //   {
  //     required: true,
  //     message: 'Please select Activity count',
  //     trigger: 'change'
  //   }
  // ],
  // date1: [
  //   {
  //     type: 'date',
  //     required: true,
  //     message: 'Please pick a date',
  //     trigger: 'change'
  //   }
  // ],
  // date2: [
  //   {
  //     type: 'date',
  //     required: true,
  //     message: 'Please pick a time',
  //     trigger: 'change'
  //   }
  // ],
  // location: [
  //   {
  //     required: true,
  //     message: 'Please select a location',
  //     trigger: 'change'
  //   }
  // ],
  // type: [
  //   {
  //     type: 'array',
  //     required: true,
  //     message: 'Please select at least one activity type',
  //     trigger: 'change'
  //   }
  // ],
  // resource: [
  //   {
  //     required: true,
  //     message: 'Please select activity resource',
  //     trigger: 'change'
  //   }
  // ],
  // desc: [{ required: true, message: 'Please input activity form', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  isSBtnLoding.value = true
  isSBtnDisable.value = true

  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.value.id = Number(ruleForm.value.id)

      // 添加
      if (ruleFormInfo.value.type === 'add') {
        // http请求
        const res = await addRole(ruleForm.value)
        if (res.code !== '2000') {
          ElMessage.error('数据添加失败')
          return
        }
        ElMessage.success('数据添加成功')
      }
      // 修改
      if (ruleFormInfo.value.type === 'edit') {
        // http请求
        const res = await editRole(ruleForm.value.id, ruleForm.value)
        if (res.code !== '2000') {
          ElMessage.error('数据修改失败')
          return
        }
        ElMessage.success('数据修改成功')
      }

      isSBtnLoding.value = false
      isSBtnDisable.value = false

      // 关闭模态框
      dialogFormVisible.value = false
      getPageData()
      // 重置表单
      formEl.resetFields()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const searchData = reactive({
  id: '',
  region: ''
})

/**
 * 搜索
 */
const onSearchSubmit = () => {
  console.log('搜索' + searchData)
}

/**
 * 获取分页数据
 */
const getPageData = async () => {
  const resRoles = await requestGetRolesPage({
    pageNum: pageParams.value.pageNum,
    pageSize: pageParams.value.pageSize
  })
  console.log(resRoles, 'resRoles')

  tableData.value = resRoles.data.list
  pageParams.value.total = resRoles.data.total
}

/**
 * 添加数据
 */
const addItemHandler = () => {
  ruleFormInfo.value = {
    type: 'add',
    title: '添加角色'
  }
  // 清空验证
  ruleFormRef.value?.clearValidate()
  // 重置表单
  ruleFormRef.value?.resetFields()
  dialogFormVisible.value = true
}

/**
 * 删除
 */
const delItemHandler = (id: string) => {
  ruleFormInfo.value = {
    type: 'del',
    title: '删除角色'
  }
  console.log(id)

  delRole(id)
}

/**
 * 修改
 */
const editItemHandler = (row: RolesType) => {
  ruleFormInfo.value = {
    type: 'edit',
    title: '修改角色'
  }

  console.log(row, 'rowrowrow')
  ruleForm.value = row
  dialogFormVisible.value = true
}

onMounted(() => {
  getPageData()
})
// 分页时间
const pageChangeHandler = (currentPage: number, pageSize: number) => {
  pageParams.value.pageNum = currentPage
  pageParams.value.pageSize = pageSize
  getPageData()
}
</script>

<style lang="scss" scoped>
.search {
  // border: 1px solid var(--el-border-color);
}

.mytable {
  // margin: 10px 0;
  // border: 1px solid var(--el-border-color);
}

.mypage {
  margin: 10px 0;
  // border: 1px solid var(--el-border-color);
}

.gongju {
  margin: 10px 0;
}
</style>
